//
//  MYGUpdateInfoViewController.swift
//  MYDoctor
//
//  Created by chenjs on 2024/4/27.
//

import UIKit

class MYGUpdateInfoViewController: MYGBaseController {
    private var contents:[Any] = []
    var model : MYGUserModel?
    var isEdit:Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configUI()
        configCell()
    }
    
    func configCell(){
        contents = []
        
        let item = MYGIDCardCellModel()
//        item.backImage = UIImage(named: "Register/frondid")
//        item.frontImage = UIImage(named: "Register/backid")
        contents.append(item)
        
        let creitem = MYGCredentialCellModel()
        creitem.title = "医师执业证"
        creitem.norImage = UIImage(named: "Register/crid")
        creitem.content = "上传注意事项：\n 1、上传执业证图片包含：\n执业证编码、头像信息、执业\n证注册信息、执业机构地点\n2、最多上传三张照片"
//        creitem.image1 = UIImage(named: "Register/icon_tianjiatup")
//        creitem.image2 = UIImage(named: "Register/icon_tianjiatup")
//        creitem.image3 = UIImage(named: "Register/icon_tianjiatup")
        contents.append(creitem)
        
        let creitem1 = MYGCredentialCellModel()
        creitem1.title = "医师资格证"
        creitem1.norImage = UIImage(named: "Register/cried")
        creitem1.content = "上传注意事项：\n1、上传资格证图片包含：\n资格证编码、头像信息、执业\n证注册信息、执业机构地点\n2、最多上传三张照片"
//        creitem1.image1 = UIImage(named: "Register/icon_tianjiatup")
//        creitem1.image2 = UIImage(named: "Register/icon_tianjiatup")
//        creitem1.image3 = UIImage(named: "Register/icon_tianjiatup")
        contents.append(creitem1)
        
        tableView.reloadData()
        
    }
    
    // MARK: - UI
    private func configUI() {
        title = "上传证件"
        
        if(!isEdit) {
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: orderButton)
        }

        view.backgroundColor = .white
        view.addSubview(tableView)
        view.addSubview(saveButton)
        saveButton.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().inset(bottomSafeheight)
            make.height.equalTo(49)
        }
        tableView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(saveButton.snp.top)
        }
        
    }
    
    private lazy var orderButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("跳过", for: .normal)
        btn.setTitleColor(.rgba(69, 131, 250, 1), for: .normal)
        btn.titleLabel?.font = .regular(13)
        btn.addTarget(self, action: #selector(clickAddBtn), for: .touchUpInside)
        return btn
    }()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(cellWithClass: MYGIdCardTableViewCell.self)
        tableView.register(cellWithClass: MYGCredentialCell.self)
        return tableView
    }()
    
    private lazy var saveButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("下一步", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .medium(17)
       // btn.backgroundColor = .rgba(162, 146, 254, 1)
        btn.addCAGradientLayerColor(colors: [UIColor.init(hexString: "#97B3FF").cgColor,
                                                 UIColor.init(hexString: "#4975EC").cgColor],
                                        startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint.init(x: 1, y: 0))
        btn.addTarget(self, action: #selector(nextAction), for: .touchUpInside)
        return btn
    }()
    
    
}
extension MYGUpdateInfoViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        contents.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return indexPath.row == 0  ? 150 : 290
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let item = contents[indexPath.row] as? MYGIDCardCellModel {
            let cell = tableView.dequeueReusableCell(withClass: MYGIdCardTableViewCell.self, for: indexPath)
            cell.model = item
            return cell
        }
        
        if let item = contents[indexPath.row] as? MYGCredentialCellModel {
            let cell = tableView.dequeueReusableCell(withClass: MYGCredentialCell.self, for: indexPath)
            cell.model = item
            return cell
        }
        
        return UITableViewCell()
    }
    
}
extension MYGUpdateInfoViewController {
    
    @objc func clickAddBtn(){
        UIViewController.keyWindow?.rootViewController = MYGTabBarController()
    }
    
    @objc func nextAction() {
        
        var images:[UIImage] = []
        let item:MYGIDCardCellModel = self.contents[0] as! MYGIDCardCellModel
        if item.frontImage == nil || item.backImage == nil {
            MMYGHUD.showToast(text: "请上传身份证件照")
            return
        }
        
        images.append(item.frontImage!)
        images.append(item.backImage!)
        
        var images1:[UIImage] = []
        let item1:MYGCredentialCellModel = self.contents[1] as! MYGCredentialCellModel
        if(item1.image1 != nil){images1.append(item1.image1!)}
        if(item1.image2 != nil){images1.append(item1.image2!)}
        if(item1.image3 != nil){images1.append(item1.image3!)}
        if images1.count == 0  {
            MMYGHUD.showToast(text: "请上传医师证件照")
            return
        }
        images1.map { image in
            images.append(image)
        }
    
        var images2:[UIImage] = []
        let item2:MYGCredentialCellModel = self.contents[2] as! MYGCredentialCellModel
        if(item2.image1 != nil){images2.append(item2.image1!)}
        if(item2.image2 != nil){images2.append(item2.image2!)}
        if(item2.image3 != nil){images2.append(item2.image3!)}
        if images2.count == 0  {
            MMYGHUD.showToast(text: "请上传医师证件照")
            return
        }
        images2.map { image in
            images.append(image)
        }
        MYGLoading.show()
        let group = DispatchGroup()
        var urls: [String] = []
        var error: String?
        for image in images {
            group.enter()
            MMYGNetwork<MYGCommonAPI, MYGEmptyModel>.request(target: .uploadOssFiles(image: image)) { _ in
                MYGLoading.hide()
            } stringBlock: { text in
                urls.append(text)
                group.leave()
            } failed: { _, err in
               error = err
                group.leave()
            }
        }
        
        group.notify(queue: DispatchQueue.main) { [self] in
            if let error = error {
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
                return
            }
            MYGLoading.show()
            
            var params:[String:Any] = [:]
            
            let ids:[String] = Array(urls.dropFirst(0).prefix(2))
            let proCount = images1.count
            let pros:[String] = Array(urls.dropFirst(2).prefix(proCount))
            
            let qulCount = images2.count
            let quls:[String] = Array(urls.dropFirst(proCount + 2 ).prefix(qulCount))
            
            params["card_images"] = ids
            params["professional"] = pros
            params["qualification"] = quls
            
            let id = model!.doctor.id
           
            MMYGNetwork<MYGRegisterAPI,MYGUserModel>.request(target: .uploadDoctorInf(id:"\(id)",params: params)) { model  in
                MYGLoading.hide()
                
                MYGUserManager.isDoctorInfComplete = true
                let user = MYGUserManager.getUser()
                user!.doctor.card_images = ids
                user!.doctor.professional = pros
                user!.doctor.qualification = quls
                
                MYGUserManager.saveUser(user!)
                
                if self.isEdit {
                    self.navigationController?.popViewController(animated: true)
                }else {
                    UIViewController.keyWindow?.rootViewController = MYGTabBarController()
                }
            } failed: { _, error in
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
            }
        }
    }
    
   
    
}

